package com.pioneer.template;

import java.lang.Integer;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
import javax.ejb.EJBException;
import javax.ejb.CreateException;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class TemplateBean implements EntityBean
{
	public int cus_id;
	public String name;
	public double balance;

	public EntityContext context;

	public Integer ejbCreate(int id, String name)
	throws CreateException
	{
		this.cus_id=id;
		this.name=name;
		this.balance=0;
		try
		{
			Connection dbConnection = getDBConnection();
			Statement stat=dbConnection.createStatement();
			int resultCount=stat.executeUpdate("INSERT INTO c01_customer values ("+cus_id+",'"+name+"',"+balance+")");
			stat.close();
		}
		catch (SQLException e)
		{
			throw new CreateException(e.getMessage());
		}
		return new Integer(0);
	}

	public void ejbPostCreate(int id, String name)	{}
	public void ejbActivate() {}
	public void ejbPassivate() {}
	public void ejbLoad() {}
	public void ejbStore() {}
	public void ejbRemove() {}

	public void setEntityContext(EntityContext newContext)
	{
		context=newContext;
	}

	public void unsetEntityContext()
	{
		context=null;
	}

	public String getName()
	{
		return name;
	}
	
	private Connection getDBConnection() throws SQLException {
         
        Connection connection=null;
         
        try {
            InitialContext ic = new InitialContext();
            DataSource ds = (DataSource)ic.lookup("java:comp/env/jdbc/Pioneer");
			
            connection = ds.getConnection("sa","");
        
        } catch (NamingException ne) {
            throw new EJBException(ne.toString());
        } catch (SQLException se) {
            throw new EJBException(se.toString());
        }

        return connection;
    }
}